/****************************************************************************
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
Copyright (c) 2019-present Axmol Engine contributors (see AUTHORS.md).

https://axmol.dev/

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/

#include "axmol/ui/UIText.h"
#include "axmol/2d/Label.h"
#include "axmol/platform/FileUtils.h"

namespace ax
{

namespace ui
{

static const int LABEL_RENDERER_Z = (-1);

IMPLEMENT_CLASS_GUI_INFO(Text)

Text::Text()
    : _touchScaleChangeEnabled(false)
    , _normalScaleValueX(1.0f)
    , _normalScaleValueY(1.0f)
    , _fontName("Thonburi")
    , _fontSize(10.f)
    , _onSelectedScaleOffset(0.5)
    , _labelRenderer(nullptr)
    , _labelRendererAdaptDirty(true)
    , _type(Type::SYSTEM)
{}

Text::~Text() {}

Text* Text::create()
{
    Text* widget = new Text();
    if (widget->init())
    {
        widget->autorelease();
        return widget;
    }
    AX_SAFE_DELETE(widget);
    return nullptr;
}

bool Text::init()
{
    if (Widget::init())
    {
        return true;
    }
    return false;
}

Text* Text::create(std::string_view textContent, std::string_view fontName, float fontSize)
{
    Text* text = new Text();
    if (text->init(textContent, fontName, fontSize))
    {
        text->autorelease();
        return text;
    }
    AX_SAFE_DELETE(text);
    return nullptr;
}

bool Text::init(std::string_view textContent, std::string_view fontName, float fontSize)
{
    bool ret = true;
    do
    {
        if (!Widget::init())
        {
            ret = false;
            break;
        }
        this->setFontName(fontName);
        this->setFontSize(fontSize);
        this->setString(textContent);
    } while (0);
    return ret;
}

void Text::initRenderer()
{
    _labelRenderer = Label::create();
    addProtectedChild(_labelRenderer, LABEL_RENDERER_Z, -1);
}

void Text::setString(std::string_view text)
{
    if (text == _labelRenderer->getString())
    {
        return;
    }
    _labelRenderer->setString(text);
    updateContentSizeWithTextureSize(_labelRenderer->getContentSize());
    _labelRendererAdaptDirty = true;
}

std::string_view Text::getString() const
{
    return _labelRenderer->getString();
}

ssize_t Text::getStringLength() const
{
    return _labelRenderer->getStringLength();
}

void Text::setFontSize(float size)
{
    if (_type == Type::SYSTEM)
    {
        _labelRenderer->setSystemFontSize(size);
    }
    else
    {
        TTFConfig config = _labelRenderer->getTTFConfig();
        config.fontSize  = size;
        _labelRenderer->setTTFConfig(config);
    }
    _fontSize = size;
    updateContentSizeWithTextureSize(_labelRenderer->getContentSize());
    _labelRendererAdaptDirty = true;
}

float Text::getFontSize() const
{
    return _fontSize;
}

void Text::setFontName(std::string_view name)
{
    if (FileUtils::getInstance()->isFileExist(name))
    {
        TTFConfig config    = _labelRenderer->getTTFConfig();
        config.fontFilePath = name;
        config.fontSize     = _fontSize;
        _labelRenderer->setTTFConfig(config);
        _type = Type::TTF;
    }
    else
    {
        _labelRenderer->setSystemFontName(name);
        if (_type == Type::TTF)
        {
            _labelRenderer->requestSystemFontRefresh();
        }
        _type = Type::SYSTEM;
    }
    _fontName = name;
    updateContentSizeWithTextureSize(_labelRenderer->getContentSize());
    _labelRendererAdaptDirty = true;
}

std::string_view Text::getFontName() const
{
    return _fontName;
}

Text::Type Text::getType() const
{
    return _type;
}

void Text::setTextAreaSize(const Vec2& size)
{
    _labelRenderer->setDimensions(size.width, size.height);
    if (!_ignoreSize)
    {
        _customSize = size;
    }
    updateContentSizeWithTextureSize(_labelRenderer->getContentSize());
    _labelRendererAdaptDirty = true;
}

const Vec2& Text::getTextAreaSize() const
{
    return _labelRenderer->getDimensions();
}

void Text::setTextHorizontalAlignment(TextHAlignment alignment)
{
    _labelRenderer->setHorizontalAlignment(alignment);
}

TextHAlignment Text::getTextHorizontalAlignment() const
{
    return _labelRenderer->getHorizontalAlignment();
}

void Text::setTextVerticalAlignment(TextVAlignment alignment)
{
    _labelRenderer->setVerticalAlignment(alignment);
}

TextVAlignment Text::getTextVerticalAlignment() const
{
    return _labelRenderer->getVerticalAlignment();
}

void Text::setTextColor(const Color32 color)
{
    _labelRenderer->setTextColor(color);
}

const Color32& Text::getTextColor() const
{
    return _labelRenderer->getTextColor();
}

void Text::setTouchScaleChangeEnabled(bool enable)
{
    _touchScaleChangeEnabled = enable;
}

bool Text::isTouchScaleChangeEnabled() const
{
    return _touchScaleChangeEnabled;
}

void Text::onPressStateChangedToNormal()
{
    if (!_touchScaleChangeEnabled)
    {
        return;
    }
    _labelRenderer->setScaleX(_normalScaleValueX);
    _labelRenderer->setScaleY(_normalScaleValueY);
}

void Text::onPressStateChangedToPressed()
{
    if (!_touchScaleChangeEnabled)
    {
        return;
    }
    _labelRenderer->setScaleX(_normalScaleValueX + _onSelectedScaleOffset);
    _labelRenderer->setScaleY(_normalScaleValueY + _onSelectedScaleOffset);
}

void Text::onPressStateChangedToDisabled() {}

void Text::onSizeChanged()
{
    Widget::onSizeChanged();
    _labelRendererAdaptDirty = true;
}

void Text::adaptRenderers()
{
    if (_labelRendererAdaptDirty)
    {
        labelScaleChangedWithSize();
        _labelRendererAdaptDirty = false;
    }
}

Vec2 Text::getVirtualRendererSize() const
{
    return _labelRenderer->getContentSize();
}

Vec2 Text::getAutoRenderSize()
{
    Vec2 virtualSize = _labelRenderer->getContentSize();
    if (!_ignoreSize)
    {
        _labelRenderer->setDimensions(0, 0);
        virtualSize = _labelRenderer->getContentSize();
        _labelRenderer->setDimensions(_contentSize.width, _contentSize.height);
    }

    return virtualSize;
}

Node* Text::getVirtualRenderer()
{
    return _labelRenderer;
}

void Text::labelScaleChangedWithSize()
{
    if (_ignoreSize)
    {
        _labelRenderer->setScale(1.0f);
        _normalScaleValueX = _normalScaleValueY = 1.0f;
    }
    else
    {
        _labelRenderer->setDimensions(_contentSize.width, _contentSize.height);
        Vec2 textureSize = _labelRenderer->getContentSize();
        if (textureSize.width <= 0.0f || textureSize.height <= 0.0f)
        {
            _labelRenderer->setScale(1.0f);
            return;
        }
        float scaleX = _contentSize.width / textureSize.width;
        float scaleY = _contentSize.height / textureSize.height;
        _labelRenderer->setScaleX(scaleX);
        _labelRenderer->setScaleY(scaleY);
        _normalScaleValueX = scaleX;
        _normalScaleValueY = scaleY;
    }
    _labelRenderer->setPosition(_contentSize.width / 2.0f, _contentSize.height / 2.0f);
}

std::string Text::getDescription() const
{
    return "Label";
}

void Text::enableShadow(const Color32& shadowColor, const Vec2& offset, int blurRadius)
{
    _labelRenderer->enableShadow(shadowColor, offset, blurRadius);
}

void Text::enableOutline(const Color32& outlineColor, int outlineSize)
{
    _labelRenderer->enableOutline(outlineColor, outlineSize);
    updateContentSizeWithTextureSize(_labelRenderer->getContentSize());
    _labelRendererAdaptDirty = true;
}

void Text::enableGlow(const Color32& glowColor)
{
    if (_type == Type::TTF)
        _labelRenderer->enableGlow(glowColor);
}

void Text::disableEffect()
{
    _labelRenderer->disableEffect();
    updateContentSizeWithTextureSize(_labelRenderer->getContentSize());
    _labelRendererAdaptDirty = true;
}

void Text::disableEffect(LabelEffect effect)
{
    _labelRenderer->disableEffect(effect);
    // only outline effect will affect the content size of label
    if (LabelEffect::OUTLINE == effect)
    {
        updateContentSizeWithTextureSize(_labelRenderer->getContentSize());
        _labelRendererAdaptDirty = true;
    }
}

bool Text::isShadowEnabled() const
{
    return _labelRenderer->isShadowEnabled();
}
Vec2 Text::getShadowOffset() const
{
    return _labelRenderer->getShadowOffset();
}
float Text::getShadowBlurRadius() const
{
    return _labelRenderer->getShadowBlurRadius();
}
Color32 Text::getShadowColor() const
{
    Color effect = _labelRenderer->getShadowColor();
    return Color32(effect.r * 255, effect.g * 255, effect.b * 255, effect.a * 255);
}

int Text::getOutlineSize() const
{
    return _labelRenderer->getOutlineSize();
}
LabelEffect Text::getLabelEffectType() const
{
    return _labelRenderer->getLabelEffectType();
}
Color32 Text::getEffectColor() const
{
    Color effect = _labelRenderer->getEffectColor();
    return Color32(effect.r * 255, effect.g * 255, effect.b * 255, effect.a * 255);
}

Sprite* Text::getLetter(int lettetIndex)
{
    return _labelRenderer->getLetter(lettetIndex);
}

void Text::setBlendFunc(const BlendFunc& blendFunc)
{
    _labelRenderer->setBlendFunc(blendFunc);
}

const BlendFunc& Text::getBlendFunc() const
{
    return _labelRenderer->getBlendFunc();
}

Widget* Text::createCloneInstance()
{
    return Text::create();
}

void Text::copySpecialProperties(Widget* widget)
{
    Text* label = dynamic_cast<Text*>(widget);
    if (label)
    {
        setFontName(label->_fontName);
        setFontSize(label->getFontSize());
        setTextColor(label->getTextColor());
        setString(label->getString());
        setTouchScaleChangeEnabled(label->_touchScaleChangeEnabled);
        setTextHorizontalAlignment(label->_labelRenderer->getHorizontalAlignment());
        setTextVerticalAlignment(label->_labelRenderer->getVerticalAlignment());
        setTextAreaSize(label->_labelRenderer->getDimensions());
        setContentSize(label->getContentSize());

        LabelEffect effectType = label->getLabelEffectType();
        if (effectType == LabelEffect::GLOW)
        {
            enableGlow(label->getEffectColor());
        }
        else if (effectType == LabelEffect::OUTLINE)
        {
            enableOutline(label->getEffectColor(), label->getOutlineSize());
        }
        if (label->isShadowEnabled())
        {
            enableShadow(label->getShadowColor(), label->getShadowOffset(), label->getShadowBlurRadius());
        }
    }
}

}  // namespace ui

}  // namespace ax
